package club.janna.netty.bio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class BioServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("服务器启动成功，监听8080");
        while(true) {
            Socket accept = serverSocket.accept();
            if(accept != null) {
                System.out.println("新建连接：" + accept.getRemoteSocketAddress());
                new Thread(() -> {
                    while(true) {
                        try {
                            InputStream inputStream = accept.getInputStream();
                            OutputStream outputStream = accept.getOutputStream();
                            byte[] bytes = new byte[1024];
                            int n;
                            System.out.println("准备读取数据...");
                            while((n = inputStream.read(bytes)) != -1) {
                                System.out.println("收到数据：" + new String(bytes, 0, n));
                                System.out.println("数据来自：" + accept.getRemoteSocketAddress());
                                outputStream.write(bytes);
                                outputStream.flush();
                                System.out.println("数据发送完毕");
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            break;
                        }
                    }
                }).start();
            }
        }
    }
}
